<template>
  <div class="cardOcr" v-if="!isShowF && !isShowZ && !isFail">
    <div class="title">请正确拍摄上传身份证正反面</div>
    <div class="tipText">照片要求：拍摄图片完整、清晰、无遮挡</div>
    <div class="takePhotoArea">
      <div class="textArea">
        <div class="areaTitle">身份证人像面</div>
        <div class="AreaText">
          <div>即身份证正面照片</div>
          <div>(包含姓名、公民身份证)</div>
        </div>
      </div>
      <div class="imgArea" @click="chooseImgZ">
        <img src="../../static/ID_card.png" alt="" class="img bgImg" />
        <img :src="ocrInfoZ.imgUrlZ" alt="" class="cardImg" />
      </div>
    </div>
    <div class="takePhotoArea">
      <div class="textArea">
        <div class="areaTitle">身份证国徽面</div>
        <div class="AreaText">
          <div>即身份证反面照片</div>
          <div>(包含有效期)</div>
        </div>
      </div>
      <div class="imgArea" @click="chooseImgF">
        <img src="../../static/ID_card_fan.png" alt="" class="img bgImg" />
        <img :src="ocrInfoF.imgUrlF" alt="" class="cardImg" />
      </div>
    </div>
    <div class="perfectInfoTitle">身份证信息</div>
    <div class="infoForm">
      <up-form labelPosition="left" :model="infoForm" labelWidth="150rpx">
        <up-form-item label="姓名" prop="name" borderBottom>
          <up-input
            v-model="ocrInfoZ.name"
            border="none"
            placeholder="请输入姓名"
          ></up-input>
        </up-form-item>
        <up-form-item label="身份证号" prop="idNum" borderBottom>
          <up-input
            v-model="ocrInfoZ.id"
            border="none"
            placeholder="请输入身份证号"
          ></up-input>
        </up-form-item>
        <up-form-item label="有效期" prop="limitDate" borderBottom>
          <up-input
            v-model="ocrInfoF.validDate"
            border="none"
            placeholder="请输入证件有效期"
          ></up-input>
        </up-form-item>
        <up-form-item label="地址" prop="infoAdress" borderBottom>
          <up-input
            v-model="ocrInfoZ.address"
            border="none"
            placeholder="请输入地址"
          ></up-input>
        </up-form-item>
      </up-form>
    </div>
    <div class="formTips">若识别信息有误，请重新拍照上传！</div>
    <div
      class="nextStepBtn"
      :class="
        ocrInfoZ.gender &&
        ocrInfoZ.nationality &&
        ocrInfoZ.address &&
        ocrInfoZ.name &&
        ocrInfoZ.id &&
        ocrInfoF.validDate &&
        ocrInfoF.authority
          ? 'done'
          : ''
      "
      @click="goNext"
    >
      下一步
    </div>
  </div>
  <up-modal
    width="500rpx"
    :show="isShowDialog"
    content="小程序需要您允许使用摄像头才能正常采集身份信息"
    confirmText="确定"
    showCancelButton
    cancelText="取消"
    @confirm="openCameraSetting"
    @cancel="isShowDialog = !isShowDialog"
  ></up-modal>
  <div class="camera" v-if="isShowZ">
    <div class="tipsText">请将身份证正面置于此区域</div>
    <div class="cameraArea">
      <camera
        class="camera"
        mode="normal"
        resolution="high"
        device-position="back"
        flash="auto"
      />
    </div>
    <div class="cameraBtn">
      <div class="cancel btn" @click="cancelZ">取消</div>
      <div class="confirm btn" @click="takePhotoZ">下一步</div>
    </div>
  </div>
  <div class="camera" v-if="isShowF">
    <div class="tipsText">请将身份证反面置于此区域</div>
    <div class="cameraArea">
      <camera
        class="camera"
        mode="normal"
        resolution="high"
        device-position="back"
        flash="auto"
      />
    </div>
    <div class="cameraBtn">
      <div class="cancel btn" @click="cancelF">取消</div>
      <div class="confirm btn" @click="takePhotoF">下一步</div>
    </div>
  </div>
  <div class="ocrFail" v-if="isFail">
    <img class="failIcon" src="../../static/fail_icon.png" alt="" />
    <div class="failTitle">身份认证失败</div>
    <div class="failTips">身份证扫描失败，请重试哦</div>
    <div class="tryAgain" @click="tryAgain">再试一次</div>
    <div class="goIndex" @click="goIndex">返回首页</div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import * as http from "../../utils/http";
import * as utils from "../../utils/utils";
import { useAppStore } from "../../store/index";
const store = useAppStore();
// 是否授权
const isAuth = ref(false);
// 是否显示弹出框
const isShowDialog = ref(false);
const goNext = () => {
  let { gender, nationality, address, name, birth, id, paramZ } = ocrInfoZ;
  let custName = name;
  let cardNo = id;
  let sex = gender;
  let nation = nationality;
  let { validDate, authority, paramF } = ocrInfoF;
  http
    .createPlayersDetail({
      custName,
      cardNo,
      sex,
      nation,
      address,
      birth,
      validDate,
      authority,
      playersId: store.bizId,
    })
    .then((res) => {
      console.log(store.custPhone);
      http
        .realNameSubmit({
          custName,
          sex,
          nation,
          birth,
          address,
          cardNo,
          authority,
          validDate,
          orderId: store.orderId,
          orderNo: store.orderNo,
          playersId: store.bizId,
          playersType: store.playersType, //参与人类型 借款人：1 保证人：2
          playersRelationType: store.playerRelationType, //参与人关系 本人：1 配偶：2 亲属：3  朋友：4  其他：9
          orderExecRcdId: store.orderExecRcdId,
          custPhone: store.custPhone,
          cardNeFileImageBase64: paramF,
          cardPrFileImageBase64: paramZ,
        })
        .then((res) => {
          store.setCardNeFileId(res.data.cardNeFileId);
          wx.setStorageSync("cardNeFileId", res.data.cardNeFileId);
          store.setCardPrFileId(res.data.cardPrFileId);
          wx.setStorageSync("cardPrFileId", res.data.cardPrFileId);

          store.setCardNeFileName(res.data.cardNeFileName);
          wx.setStorageSync("cardNeFileName", res.data.cardNeFileName);
          store.setCardPrFileName(res.data.cardPrFileName);
          wx.setStorageSync("cardPrFileName", res.data.cardPrFileName);
          http
            .createCd({
              custName,
              sex,
              nation,
              birth,
              address,
              cardNo,
              authority,
              validDate,
              cardNeFileId: store.cardNeFileId,
              cardPrFileId: store.cardPrFileId,
            })
            .then((res) => {
              let a = {
                custName,
                cardNo,
                sex,
                nation,
                birth,
                address,
                authority,
                validDate,
                custPhone: store.custPhone,
                orderId: store.orderId,
                bizId: store.bizId,
                bizType: store.playersType,
              };
              wx.redirectTo({
                url: "../readProtocol/readProtocol?value=" + JSON.stringify(a),
              });
            });
        });
    });
};
// 进入页面获取授权
onMounted(() => {
  getAuth(); //获取授权
  // 获取经纬度
  utils.getGps().then((res) => {
    let longitudeAndLatitude = `${res.longitude},${res.latitude}`;
    // 创建订单
    http
      .createOrder(
        { longitudeAndLatitude },
        { "Access-Control-Allow-Origin": "https:dm-dev.hfrcbc.com/hfrcbc-xfd" }
      )
      .then((res) => {
        // 订单id
        store.setOrderId(res.data.orderId);
        // 订单编号
        store.setOrderNo(res.data.orderNo);
        // 创建订单执行记录
        http.createOrderExecRcd({ orderNo: store.orderNo }).then((res) => {
          if (res.message == "创建订单执行记录成功") {
            // 订单执行记录id
            store.setOrderExecRcdId(res.data);
            console.log("创建订单执行记录成功");
            // 获取ip
            utils.getIp().then((res) => {
              let ipAddress = res;
              // 创建参与人
              http
                .createPlayers({
                  playersType: store.playersType,
                  playersRelationType:store.playerRelationType,
                  orderId: store.orderId,
                  ipAddress,
                })
                .then((res) => {
                  if (res.message == "创建参与人成功") {
                    console.log("创建参与人成功");
                    // 参与人id
                    store.setBizId(res.data);
                  }
                });
            });
          }
        });
      });
  });
});
// 获取授权
const getAuth = () => {
  wx.getSetting({
    success: (res) => {
      if (!res.authSetting["scope.camera"]) {
        wx.authorize({
          scope: "scope.camera",
          success: () => {
            isAuth.value = true;
          },
          fail: () => {
            isShowDialog.value = true;
          },
        });
      } else {
        isAuth.value = true;
      }
    },
  });
};
// 打开小程序设置
const openCameraSetting = () => {
  wx.getSetting({
    success: (res) => {
      if (res.authSetting && !res.authSetting["scope.camera"]) {
        wx.openSetting({
          success: (res) => {
            if (res.authSetting && res.authSetting["scope.camera"]) {
              isAuth.value = true;
              wx.showToast({
                title: "您已授权使用摄像头",
                icon: "none",
              });
            } else {
              isShowDialog.value = true;
            }
          },
        });
      } else {
      }
    },
  });
};
// 将图片转成base64
const getBase64Data = (path) => {
  return new Promise((resolve, reject) => {
    wx.getFileSystemManager().readFile({
      filePath: path,
      encoding: "base64",
      success(res) {
        resolve(res);
      },
      fail(res) {
        reject(res);
      },
    });
  });
};

// 是否显示正面
const isShowZ = ref(false);
// 点击正面弹出相机
const chooseImgZ = () => {
  wx.showLoading({
    title: "",
    mask: true,
  });
  wx.getSetting({
    success: (res) => {
      wx.hideLoading();
      if (res.authSetting && !res.authSetting["scope.camera"]) {
        isShowDialog.value = true;
      } else {
        isShowZ.value = true;
      }
    },
  });
};
// ocr识别正面信息
const ocrInfoZ = reactive({
  gender: "", //性别
  nationality: "", //民族
  address: "", //住址
  name: "", //姓名
  birth: "", //出生日期
  id: "", //身份证号码
  imgUrlZ: "", //回显正面
  paramZ: "", //上传给后台的正面
});
// 拍照--人像面--正面
const takePhotoZ = () => {
  const ctx = uni.createCameraContext();
  ctx.takePhoto({
    quality: "normal",
    success: (res) => {
      isShowZ.value = false;
      wx.showLoading({
        title: "识别中",
        mask: true,
      });
      getBase64Data(res.tempImagePath).then((res) => {
        let base64Data = res.data;
        base64Data = wx.arrayBufferToBase64(wx.base64ToArrayBuffer(base64Data));
        http
          .realNameAuth({
            imageBase64: base64Data,
          })
          .then((res) => {
            if (!res.data.custName) {
              wx.hideLoading();
              wx.showToast({
                title: "请拍摄人像面",
                icon: "none",
                duration: 1500,
                mask: true,
              });
              return;
            }
            if (
              !res.data.custName ||
              !res.data.cardNo ||
              res.data.cardNo.length != 18
            ) {
              wx.hideLoading();
              wx.showToast({
                title: "证件信息扫描失败",
                icon: "none",
                duration: 1500,
                mask: true,
              });
              return;
            } else {
              wx.hideLoading();
              ocrInfoZ.gender = res.data.sex;
              ocrInfoZ.nationality = res.data.nation;
              ocrInfoZ.address = res.data.address;
              ocrInfoZ.name = res.data.custName;
              store.setUserName(res.data.custName);
              ocrInfoZ.id = res.data.cardNo;
              ocrInfoZ.birth = res.data.birth;
              ocrInfoZ.imgUrlZ = `data:image/png;base64,${base64Data}`;
              ocrInfoZ.paramZ = base64Data;
            }
          })
          .catch((err) => {
            console.log("识别失败", err);
            wx.hideLoading();
            wx.showToast({
              title: "识别失败",
              icon: "none",
              duration: 1500,
              mask: true,
            });
          });
      });
    },
    fail: (res) => {
      isShowZ.value = false;
      wx.showLoading({
        title: "识别失败",
        mask: true,
      });
      wx.hideLoading();
    },
  });
};
// 取消拍照--人像面--正面
const cancelZ = () => {
  isShowZ.value = false;
};

// 是否回显反面
const isShowF = ref(false);
// 点击反面弹出相机
const chooseImgF = () => {
  wx.showLoading({
    title: "",
    mask: true,
  });
  wx.getSetting({
    success: (res) => {
      wx.hideLoading();
      if (res.authSetting && !res.authSetting["scope.camera"]) {
        isShowDialog.value = true;
      } else {
        isShowF.value = true;
      }
    },
  });
};
// ocr识别反面信息
const ocrInfoF = reactive({
  startDate: "", //证件启始日
  endDate: "", //证件过期日
  validDate: "", //证件有效期
  authority: "", //签发机关
  imgUrlF: "", //回显反面
  paramF: "", //上传给后台的反面
});
// 拍照--国徽面--反面
const takePhotoF = () => {
  const ctx = uni.createCameraContext();
  ctx.takePhoto({
    quality: "normal",
    success: (res) => {
      isShowF.value = false;
      wx.showLoading({
        title: "识别中",
        mask: true,
      });
      getBase64Data(res.tempImagePath).then((res) => {
        let base64Data = res.data;
        base64Data = wx.arrayBufferToBase64(wx.base64ToArrayBuffer(base64Data));
        http
          .realNameAuth({ imageBase64: base64Data })
          .then((res) => {
            if (res.data.custName) {
              wx.hideLoading();
              wx.showToast({
                title: "请扫描国徽面",
                icon: "none",
                duration: 1500,
                mask: true,
              });
              return;
            }
            if (!res.data.validDate) {
              wx.hideLoading();
              wx.showToast({
                title: "证件信息扫描失败",
                icon: "none",
                duration: 1000,
                mask: true,
              });
              return;
            } else {
              if (res.data.validDate.length == 17) {
                let day1 =
                  res.data.validDate.substring(9, 13) +
                  "-" +
                  res.data.validDate.substring(13, 15) +
                  "-" +
                  res.data.validDate.substring(15, 17);
                if (day1 == "0000-00-00") {
                  res.data.validDate =
                    res.data.validDate.substring(0, 9) + "长期";
                }
                console.log(day1);
                let day2 = utils.getNowFormatDate();
                console.log(day2);
                if (day1 != "0000-00-00" && new Date(day1) < new Date(day2)) {
                  wx.hideLoading();
                  wx.showToast({
                    title: "证件已过期",
                    icon: "none",
                    duration: 1000,
                    mask: true,
                  });
                  return;
                }
              }
              wx.hideLoading();
              ocrInfoF.startDate = res.data.validDate.split("-")[0];
              ocrInfoF.endDate = res.data.validDate.split("-")[1];
              ocrInfoF.authority = res.data.authority;
              ocrInfoF.validDate = res.data.validDate;
              ocrInfoF.imgUrlF = `data:image/png;base64,${base64Data}`;
              ocrInfoF.paramF = base64Data;
              console.log(ocrInfoF, "ocrInfoF");
            }
          })
          .catch((err) => {
            console.log("识别失败", err);
            wx.hideLoading();
            wx.showToast({
              title: "识别失败",
              icon: "none",
              duration: 1500,
              mask: true,
            });
          });
      });
    },
    fail: (res) => {
      isShowF.value = false;
      wx.showToast({
        title: "识别失败",
        mask: true,
      });
      wx.hideLoading();
    },
  });
};
// 取消拍照--国徽面--反面
const cancelF = () => {
  isShowF.value = false;
};

// 是否显示验证失败
const isFail = ref(false);
const tryAgain = () => {
  wx.redirectTo({ url: "../cardOcrFirstPage/cardOcrFirstPage" });
};
const goIndex = () => {
  wx.switchTab({ url: "../../pages/index/index" });
};
</script>
<style>
page {
  background-color: #fff;
}
</style>
<style scoped lang="scss">
.ocrFail {
  .failIcon {
    width: 203rpx;
    height: 225rpx;
    margin: 43rpx calc(calc(100vw - 203rpx) / 2);
    margin-bottom: 26rpx;
  }
  .failTitle {
    height: 59rpx;
    line-height: 59rpx;
    color: #3c3c3d;
    font-size: 42rpx;
    text-align: center;
    margin-bottom: 24rpx;
  }
  .failTips {
    height: 45rpx;
    line-height: 45rpx;
    color: #333333;
    font-size: 32rpx;
    text-align: center;
  }
  .tryAgain {
    width: 590rpx;
    height: 88rpx;
    line-height: 88rpx;
    text-align: center;
    font-size: 32rpx;
    border-radius: 44rpx;
    background-image: linear-gradient(to right, #619df1, #4478c1);
    color: #fff;
    margin: 186rpx 80rpx 30rpx 80rpx;
  }
  .goIndex {
    width: 590rpx;
    height: 88rpx;
    line-height: 88rpx;
    text-align: center;
    font-size: 32rpx;
    border-radius: 44rpx;
    border: 2rpx solid #b6b6b6;
    margin: 0 80rpx;
  }
}
.cardOcr {
  .title {
    height: 45rpx;
    line-height: 45rpx;
    color: #333333;
    font-size: 32rpx;
    text-align: center;
    margin-top: 31rpx;
  }

  .tipText {
    height: 33rpx;
    line-height: 33rpx;
    text-align: center;
    color: #333333;
    font-size: 24rpx;
  }

  .takePhotoArea {
    width: 690rpx;
    height: 320rpx;
    margin: 20rpx 30rpx;
    border-radius: 16rpx;
    box-shadow: 0 4rpx 20rpx 0 rgba(0, 0, 0, 0.1);
    display: flex;
    justify-content: space-around;
    align-items: center;

    .textArea {
      width: 35%;
      .areaTitle {
        margin-bottom: 15rpx;
        height: 40rpx;
        line-height: 40rpx;
        font-size: 28rpx;
        text-align: center;
        color: #333333;
      }

      .AreaText {
        font-size: 24rpx;
        text-align: center;
      }
    }

    .imgArea {
      width: 348rpx;
      height: 230rpx;
      position: relative;

      .img {
        width: 100%;
        height: 100%;
      }

      .cardImg {
        width: 230rpx;
        height: 348rpx;
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%) rotate(-90deg);
      }

      .bgImg {
        position: absolute;
        z-index: -888;
      }
    }
  }

  .perfectInfoTitle {
    margin-left: 50rpx;
    height: 40rpx;
    line-height: 40rpx;
    font-size: 28rpx;
    color: #333333;
  }

  .infoForm {
    margin: 0 58rpx;
  }

  .formTips {
    height: 74rpx;
    line-height: 74rpx;
    text-align: center;
    color: rgba(0, 0, 0, 0.45);
  }
  .nextStepBtn {
    margin: 43rpx 80rpx;
    width: 590rpx;
    height: 106rpx;
    line-height: 106rpx;
    border-radius: 53rpx;
    background-color: #3277f2;
    font-size: 34rpx;
    text-align: center;
    color: #fff;
    opacity: 50%;
  }
  .done {
    opacity: 1;
  }
}
.camera {
  .cameraArea {
    background-color: #484849;
    width: 100vw;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    .camera {
      border: 1rpx dashed rgba($color: #000000, $alpha: 0.7);
      height: 832rpx;
      width: 520rpx;
      height: 832rpx;
      width: 520rpx;
    }
  }
  .tipsText {
    width: 360rpx;
    height: 42rpx;
    line-height: 42rpx;
    color: #4d8ced;
    font-size: 30rpx;
    position: absolute;
    top: 50%;
    transform: translate(0, -50%) rotate(90deg);
    left: -100rpx;
  }
  .cameraBtn {
    width: 100%;
    height: 148rpx;
    position: absolute;
    bottom: 115rpx;
    left: 0;
    display: flex;
    justify-content: space-around;
    align-items: center;
    text-align: center;
    .btn {
      color: #fff;
      transform: rotate(90deg);
    }
    .confirm {
      width: 148rpx;
      height: 68rpx;
      line-height: 68rpx;
      background-color: #4d8ced;
      border-radius: 34rpx;
    }
  }
}
</style>
